package com.example.camerafull;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.FloatMath;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Gallery;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.mfsoft.camera.R;

@SuppressWarnings("deprecation")
public class Compositing_photo extends Activity implements OnTouchListener {

	// Variable custom layout
	LinearLayout layoutMenuBar;
	LinearLayout layoutImage;
	LinearLayout layoutCompositing;
	LinearLayout layoutChoose;
	LinearLayout layoutButton;
	FrameLayout frameImage;
	ImageView imgFrame;
	ImageView imgPhoto;
	Gallery galleryCompositing;
	Context context;

	Drawable drawableImage;

	int image = R.drawable.image2;

	HorizontalScrollView scrollFrame;
	Button btnChooseImage;
	Button btnFr[];
	Button btnFrame, btnEffect, btnIcon, btnText, btnSave, btnShare;

	private int scrWidth;
	private int scrHeight;

	boolean isFrameClick = false;

	// Array frame variable
	int[] frame = {R.drawable.frame1, R.drawable.frame3 };
	int[] mask ={R.drawable.mask1, R.drawable.mask3};

	// Variable for custom move and Zoom image
	private static final String TAG = "Touch";
	// These matrices will be used to move and zoom image
	Matrix matrix = new Matrix();
	Matrix savedMatrix = new Matrix();

	// We can be in one of these 3 states
	static final int NONE = 0;
	static final int DRAG = 1;
	static final int ZOOM = 2;
	int mode = NONE;

	// Remember some things for zooming
	PointF start = new PointF();
	PointF mid = new PointF();
	float oldDist = 1f;
	FrameLayout frameLayout;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_ghep_anh);

		Display display = getWindowManager().getDefaultDisplay();
		scrWidth = display.getWidth();
		scrHeight = display.getHeight();
		isFrameClick = true;
		frameLayout = (FrameLayout) findViewById(R.id.frameLayout);
		customLayout();

	}

	public void customLayout() {

		// TODO custom layout Menu Bar
		layoutMenuBar = (LinearLayout) findViewById(R.id.layoutMenubar);
		layoutMenuBar.getLayoutParams().width = scrWidth;
		layoutMenuBar.getLayoutParams().height = scrHeight / 8;

		frameImage = (FrameLayout) findViewById(R.id.frameLayout);
		frameImage.getLayoutParams().width = scrWidth;
		frameImage.getLayoutParams().height = 4 * scrHeight / 7;

		// TODO draw image into image view
		Drawable dr = getResources().getDrawable(image);
		Bitmap bitmap = ((BitmapDrawable) dr).getBitmap();
		drawableImage = new BitmapDrawable(getResources(),
				Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(),
						bitmap.getHeight(), true));
		imgPhoto = (ImageView) findViewById(R.id.imageView);
		imgPhoto.getLayoutParams().width = LayoutParams.WRAP_CONTENT;
		imgPhoto.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
		imgPhoto.setImageDrawable(drawableImage);
		// TODO Handle onTouch image
		imgPhoto.setOnTouchListener(this);
		
		// TODO draw Frame
		imgFrame = new ImageView(getApplicationContext());
		imgFrame.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT));
		Drawable drFrame = getResources().getDrawable(R.drawable.frame1);
		Bitmap bmFrame = ((BitmapDrawable) drFrame).getBitmap();
		Drawable drawableFrame = new BitmapDrawable(getResources(),
				Bitmap.createScaledBitmap(bmFrame, bitmap.getWidth(),
						bitmap.getHeight(),
						true));
		imgFrame.setImageDrawable(drawableFrame);
//		frameImage.addView(imgFrame);

		// TODO custom layout and set Button(Frame, Effect, ...)
		layoutCompositing = (LinearLayout) findViewById(R.id.layoutCompositing);
		layoutCompositing.getLayoutParams().width = scrWidth;
		layoutCompositing.getLayoutParams().height = scrHeight / 4;

		// TODO custom Gallery
		galleryCompositing = (Gallery) findViewById(R.id.galleryCompositing);
		galleryCompositing.getLayoutParams().width = scrWidth;
		galleryCompositing.getLayoutParams().height = scrHeight / 8;
		galleryCompositing.setAdapter(new AddImgAdp(this));
		galleryCompositing.setVisibility(Gallery.INVISIBLE);
		galleryCompositing.setOnItemClickListener(new OnItemClickListener() {
            @SuppressWarnings("rawtypes")
			public void onItemClick(AdapterView parent, View v, int position, long id) {
            	// Do something
//            	Log.d("LOG_POSITION", "position = "+position);
        			makeMaskImage(imgPhoto, image, mask[position], frame[position]);
            }
        });

		// TODO custom buttons Frame, Effect,...
		layoutButton = (LinearLayout) findViewById(R.id.layoutButton);
		layoutButton.getLayoutParams().width = scrWidth;
		layoutButton.getLayoutParams().height = scrHeight / 8;

		// TODO custom and setOnclick for Button Frame
		btnFrame = (Button) findViewById(R.id.btnAddFrame);
		btnFrame.getLayoutParams().width = scrWidth / 6;
		btnFrame.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
		btnFrame.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (isFrameClick) {
					isFrameClick = false;
					galleryCompositing.setVisibility(Gallery.VISIBLE);
				} else {
					isFrameClick = true;
					galleryCompositing.setVisibility(Gallery.INVISIBLE);
				}
			}
		});

		// TODO custom and setOnclick for Button Effect
		btnEffect = (Button) findViewById(R.id.btnAddEffect);
		btnEffect.getLayoutParams().width = scrWidth / 6;
		btnEffect.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
		btnEffect.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(), "EFFECT",
						Toast.LENGTH_SHORT).show();
			}
		});
		// TODO custom and setOnclick for Button Icon
		btnIcon = (Button) findViewById(R.id.btnAddIcon);
		btnIcon.getLayoutParams().width = scrWidth / 6;
		btnIcon.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
		btnIcon.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(), "ICON",
						Toast.LENGTH_SHORT).show();
			}
		});

		// TODO custom and setOnclick for Button Text
		btnText = (Button) findViewById(R.id.btnAddText);
		btnText.getLayoutParams().width = scrWidth / 6;
		btnText.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
		btnText.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(), "TEXT",
						Toast.LENGTH_SHORT).show();
			}
		});
		// TODO custom and setOnclick for Button Save
		btnSave = (Button) findViewById(R.id.btnAddSave);
		btnSave.getLayoutParams().width = scrWidth / 6;
		btnSave.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
		btnSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(), "SAVE",
						Toast.LENGTH_SHORT).show();
				imgPhoto.setScaleType(ScaleType.CENTER);
			}
		});
		// TODO custom and setOnclick for Button Share
		btnShare = (Button) findViewById(R.id.btnAddShare);
		btnShare.getLayoutParams().width = scrWidth / 6;
		btnShare.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
		btnShare.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(), "SHARE",
						Toast.LENGTH_SHORT).show();
			}
		});

	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		ImageView view = (ImageView) v;
		// Dump touch event to log
		dumpEvent(event);
		// Handle touch events here...
		switch (event.getAction() & MotionEvent.ACTION_MASK) {
		case MotionEvent.ACTION_DOWN:
			savedMatrix.set(matrix);
			start.set(event.getX(), event.getY());
			Log.d(TAG, "mode=DRAG");
			mode = DRAG;
			break;
		case MotionEvent.ACTION_POINTER_DOWN:
			oldDist = spacing(event);
			Log.d(TAG, "oldDist=" + oldDist);
			if (oldDist > 10f) {
				savedMatrix.set(matrix);
				midPoint(mid, event);
				mode = ZOOM;
				Log.d(TAG, "mode=ZOOM");
			}
			break;
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_POINTER_UP:
			mode = NONE;
			Log.d(TAG, "mode=NONE");
			break;
		case MotionEvent.ACTION_MOVE:
			if (mode == DRAG) {
				// ...
				matrix.set(savedMatrix);
				matrix.postTranslate(event.getX() - start.x, event.getY()
						- start.y);
			} else if (mode == ZOOM) {
				float newDist = spacing(event);
				Log.d(TAG, "newDist=" + newDist);
				if (newDist > 10f) {
					matrix.set(savedMatrix);
					float scale = newDist / oldDist;
					matrix.postScale(scale, scale, mid.x, mid.y);
				}
			}
			break;
		}

		view.setImageMatrix(matrix);
		return true;
	}

	/** Show an event in the LogCat view, for debugging */
	private void dumpEvent(MotionEvent event) {
		String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",
				"POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
		StringBuilder sb = new StringBuilder();
		int action = event.getAction();
		int actionCode = action & MotionEvent.ACTION_MASK;
		sb.append("event ACTION_").append(names[actionCode]);
		if (actionCode == MotionEvent.ACTION_POINTER_DOWN
				|| actionCode == MotionEvent.ACTION_POINTER_UP) {
			sb.append("(pid ").append(
					action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
			sb.append(")");
		}
		sb.append("[");
		for (int i = 0; i < event.getPointerCount(); i++) {
			sb.append("#").append(i);
			sb.append("(pid ").append(event.getPointerId(i));
			sb.append(")=").append((int) event.getX(i));
			sb.append(",").append((int) event.getY(i));
			if (i + 1 < event.getPointerCount())
				sb.append(";");
		}
		sb.append("]");
		Log.d(TAG, sb.toString());
	}

	/** Determine the space between the first two fingers */
	@SuppressLint("FloatMath")
	private float spacing(MotionEvent event) {
		float x = event.getX(0) - event.getX(1);
		float y = event.getY(0) - event.getY(1);
		return FloatMath.sqrt(x * x + y * y);
	}

	/** Calculate the mid point of the first two fingers */
	private void midPoint(PointF point, MotionEvent event) {
		float x = event.getX(0) + event.getX(1);
		float y = event.getY(0) + event.getY(1);
		point.set(x / 2, y / 2);
	}

	public class AddImgAdp extends BaseAdapter {
		int galleryItem;
		private Context context;

		public AddImgAdp(Context c) {
			context = c;
			TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme);
			galleryItem = typArray.getResourceId(
					R.styleable.GalleryTheme_android_galleryItemBackground, 0);
			typArray.recycle();
		}

		public int getCount() {
			return frame.length;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imgView = new ImageView(context);
			imgView.setImageResource(frame[position]);
			imgView.setLayoutParams(new Gallery.LayoutParams(80, 70));
			imgView.setScaleType(ImageView.ScaleType.FIT_XY);
			imgView.setBackgroundResource(galleryItem);

			return imgView;
		}
	}

	public void makeMaskImage(ImageView imgView, int contentImage,
			int contentMask, int contentFrame) {
		
		Bitmap bitmapMask = BitmapFactory.decodeResource(getResources(),contentMask);//mask
		
		Bitmap bitmapOriginal = BitmapFactory.decodeResource(getResources(),contentImage);//image
		Bitmap bitmapFrame = BitmapFactory.decodeResource(getResources(),contentFrame);//image
	//	Bitmap scaleOriginal = Bitmap.createScaledBitmap(bitmapOriginal,bitmapMask.getWidth(), bitmapMask.getHeight(), true);

		//Bitmap bitmapResource = Bitmap.createBitmap(bitmapMask.getWidth(),bitmapMask.getHeight(), Config.ARGB_8888);

	/*	Canvas canvas = new Canvas(bitmapResource);
		Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
		canvas.drawBitmap(scaleOriginal, 0, 0, null);
		canvas.drawBitmap(bitmapMask, 0, 0, paint);
		paint.setXfermode(null);*/
		//imgView.setImageBitmap(contentFrame);//bitmapResource
		////imgView.setImageResource(contentFrame);
//		imgView.setScaleType(ScaleType.CENTER);

		//imgView.setBackgroundResource(contentImage);
		
		//nam fix
		int width = getWindowManager().getDefaultDisplay().getWidth();
		Bitmap bmResource = Bitmap.createBitmap(width,500, Config.ARGB_8888);
		Canvas c = new Canvas(bmResource);
		Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
		c.drawBitmap(bitmapOriginal, 0,0, paint);
		c.drawBitmap(bitmapFrame, 0,0, paint);
		imgView.setImageBitmap(bmResource);
	}
}
